<template>
    <div id="risk-order-content" class="order-content">
        <!-- 指令相关 -->
        <el-row class="risk-order-top">
            <el-col :span="12" class="form-col col-box">
                <!-- 指令表单 -->
                <div class="form-content">
                    <FuturesOrder
                        :key="renderCountKey"
                        :detail="detail"
                        :notMesh="true"
                        @handleSettingValue="handleSettingValue(arguments)"
                        @getStockInfo="getStockInfo(arguments)"
                        @getFutureRatio="getFutureRatio"
                    />
                </div>

                <el-row class="form-operate">
                    <el-col :span="7">
                        <i name="entrySetting" style="font-size: 25px" class="el-icon-setting iconClass" @click="openEntryGroup"></i>
                    </el-col>
                    <el-col :span="17">
                        <el-button name="重置" @click="handleClickButtonReset">重置</el-button>
                        <el-button name="试算" type="primary" size="mini" @click="handleTestClick">试算</el-button>
                        <el-button name="下单" type="primary" size="mini" @click="handlePlaceOrderClick">下单</el-button>
                    </el-col>
                </el-row>
            </el-col>
            <!-- 持仓信息 -->
            <el-col :span="12" class="col-box">
                <el-tabs type="card" v-model="activePane">
                    <el-tab-pane label="产品持仓信息" name="1">
                        <risk-table
                            class="position"
                            :key="positionTableKey"
                            :msg="fundPositionsListMsg"
                            @getList="getFundPositionList"
                            @handleFilter="handleFilterFundPosition"
                        ></risk-table>
                    </el-tab-pane>
                </el-tabs>
            </el-col>
        </el-row>

        <!-- 试算结果 -->
        <el-row class="risk-order-bottom">
            <h3>
                <el-row class="result-span">
                    <el-col :span="3">
                        <span>风控结果:</span>
                        <status-tag :code="riskResult"></status-tag>
                    </el-col>
                    <el-col :span="6">
                        <span>试算/下单时间: </span>
                        <span style="color: red">{{ calcTime }}</span>
                    </el-col>
                    <el-col :span="5">
                        <span>计算耗时: </span>
                        <span style="color: red">{{ takeTime }}</span>
                    </el-col>
                    <el-col :span="6">
                        <span>条目检查数:</span>
                        <span v-show="riskResultTable.length" style="color: red">{{ riskResultTable.length }}</span>
                    </el-col>
                    <el-col :span="4">
                        <el-button style="float: right" type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
                    </el-col>
                </el-row>
            </h3>
            <div style="height: calc(100% - 35px)">
                <vxe-table
                    ref="resultTable"
                    :key="tableKey"
                    :auto-resize="true"
                    :data="riskResultTable"
                    border
                    size="mini"
                    style="width: 100%"
                    height="100%"
                    v-loading="calcLoading"
                    resizable
                    :resizable-config="{ minWidth: '60' }"
                    :sort-config="{ sortMethod: customSortMethod, defaultSort: { field: 'thresholdType', order: 'desc' } }"
                    show-header-overflow
                    header-align="center"
                >
                    <vxe-column
                        v-for="(item, index) in showFieldList"
                        :key="index + item.id"
                        :field="item.id"
                        :title="item.content"
                        :sortable="item.sortable"
                        :column-config="{ isHover: true }"
                        :row-config="{ isHover: true }"
                        :filters="item.filters"
                        :filter-method="item.filterMethod"
                        :filter-render="{ name: 'FilterInput' }"
                        show-overflow
                        min-width="120"
                    >
                        <template
                            #filter="{ $panel, column }"
                            v-if="
                                [
                                    'fundCode',
                                    'fundNameSt',
                                    'assetCode',
                                    'assetName',
                                    'fundAccountCode',
                                    'fundAccountName',
                                    'stockCode',
                                    'stockNameSt',
                                    'entryCode',
                                    'entryName',
                                ].includes(item.id)
                            "
                        >
                            <div>
                                <el-input
                                    class="my-input"
                                    type="type"
                                    v-for="(option, index) in column.filters"
                                    :key="index"
                                    v-model="option.data"
                                    @input="$panel.changeOption($event, !!option.data, option)"
                                />
                            </div>
                        </template>
                        <template slot-scope="scope">
                            <span v-if="item.id === 'entryType'">{{ entryType[scope.row.entryType] }}</span>
                            <span v-else-if="item.id === 'compareType'">{{ compareDirection[scope.row.compareType] }}</span>
                            <status-tag v-else-if="item.id === 'thresholdType'" :code="scope.row.thresholdType" />
                            <branch-tag v-else-if="item.id === 'branchNum'" :data="scope.row" />
                            <span v-else-if="['investableBalance', 'maxTradable', 'maxTradableMerge'].includes(item.id)">
                                <el-popover
                                    v-if="getObjectLength(scope.row[item.id]) && getObjectLength(scope.row[item.id]) > 1"
                                    placement="top"
                                    trigger="hover"
                                >
                                    <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in scope.row[item.id]" :key="key">
                                        {{ '阀值' + ++index + getShowName(item.id) + ': ' + scope.row[item.id][getParamName(item.id) + index] }}
                                    </div>
                                    <el-tag slot="reference">{{ getObjectLength(scope.row[item.id]) + '个' + getShowName(item.id) }}</el-tag>
                                </el-popover>
                                <span
                                    v-else-if="getObjectLength(scope.row[item.id])"
                                    v-for="(value, key) in scope.row[item.id]"
                                    :key="key"
                                    style="float: right"
                                    >{{ value }}</span
                                >
                                <span v-else style="float: right"> --</span>
                            </span>
                            <span v-else-if="item.id === 'thresholdValue'" style="float: right">{{
                                scope.row[item.id] != undefined ? numberFormat(scope.row[item.id], scope.row.unit) + unitShow(scope.row.unit) : '--'
                            }}</span>

                            <span v-else-if="item.id === 'calculateValue'" style="float: right">
                                {{
                                    scope.row[item.id] != undefined
                                        ? numberFormat(scope.row[item.id], !scope.row.unit || scope.row.unit == '无' ? 2 : scope.row.unit) +
                                          unitShow(scope.row.unit)
                                        : '--'
                                }}
                            </span>
                            <span v-else>{{ scope.row[item.id] || '--' }}</span>
                        </template>
                    </vxe-column>
                </vxe-table>
                <!-- <el-pagination
                    background
                    @current-change="pageChangeResult"
                    layout=" total, prev, pager, next"
                    :current-page="pageResult.currentPage"
                    :page-size="pageResult.pageSize"
                    :total="pageResult.total"
                >
                </el-pagination> -->
            </div>
        </el-row>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="FUTURES_TRIAL"
            @on-submit="onSubmit"
        />

        <EntryGroupSetting
            v-if="transDialog"
            :resourceCode="resourceCode"
            :transDialog="transDialog"
            @getEntryGroup="getEntryGroup"
            @closeEntryDialog="closeEntryDialog"
        />
        <!--处理下单后的弹窗-->
        <RiskOrderResultAfter
            v-if="orderCancelShow"
            :key="riskOrderResultAfterKey"
            :riskResultThresholdType="result"
            :res="riskOrderResultTable"
            @riskResultContinue="riskResultContinue"
            @riskResultCancel="riskResultCancel"
        />
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import { getActiveMenuCode, getUser } from '@/utils/user-util';
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { SGU_CACHE } from '@/utils/diction-const-util';
import { getCurrentPageData, numberFormat, unitShow, NumberToWords, UUID } from '@/utils/tools';
import ColumnUtil from '../utils/column-util';
import RiskTable from '@/common/components/risk-table.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import EntryGroupSetting from '../components/entry-group-seting.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { Row } from 'element-ui';
import { getBusinessType } from '../api';
import RiskOrderResultAfter from '@/pages/risk-time/components/risk-order-result-after.vue';
import { cancelCommonOrder, trialCalculate } from '@/common/api/instruction';
import FuturesOrder from '@/pages/risk-time/components/futrues-order.vue';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'FuturesRiskOrder',
    components: {
        RiskEntryInput,
        RiskTable,
        RiskTableLayout,
        StatusTag,
        BranchTag,
        EntryGroupSetting,
        RiskInputNumber,
        RiskOrderResultAfter,
        FuturesOrder,
    },
})
export default class FuturesRiskOrder extends Vue {
    @Prop()
    detail: any;
    ColumnUtil = new ColumnUtil();
    numberFormat = numberFormat;
    unitShow = unitShow;

    // 分页
    pages = { currentPage: 1, pageSize: 25 };

    // 指令数量单位
    orderAmountUnit = {
        JJ: '份',
        GP: '股',
        ZQ: '张',
    };

    // 下单类型转换
    InstTypePojo = {
        '1': '1',
        '2': '1',
        '3': '2',
        '4': '2',
        '5': '3',
        '6': '1',
        '7': '6',
        '8': '8',
    };

    Invest: any = new Invest(); // 指令相关字典类
    entryType = {}; // 风险类型字典
    compareDirection = {}; // 比较方向字典
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    opponentCodeSelectData: any[] = []; // 交易对手方下拉数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据

    allStockType: any[] = []; // 所有证券类别数据
    stockTypePojo: any = {};
    allOrderDirection: any[] = []; // 所有订单方向数据
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态

    calcTime: string = ''; // 下单/试算时间
    takeTime: string | number = ''; // 计算耗时
    riskResult: string | number = ''; // 风控结果
    riskResultTable: any[] = []; // 风控结果表数据

    result: string = ''; // 试算结果

    activePane: string = '1'; // 持仓显示的标签页

    // 产品持仓信息相关
    fundPositionsListMsg = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.FuturesPositionColumns,
        height: '100%',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    layoutDialog: boolean = false; // 布局设置弹框显示

    // 试算结果表格全部字段
    tableColumns = this.ColumnUtil.riskTableColumns;
    // 要显示的表格列
    showFieldList: any[] = [];
    // 已选择字段列表
    selectedFieldList: any[] = [];
    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '产品代码', id: 'fundCode', sortable: true },
        { content: '产品名称', id: 'fundNameSt', sortable: false },
    ];

    iconDom: any = null; // 试算结果表筛选图标dom
    tableKey: number = 0;
    calcLoading: boolean = false;
    entryTypeArr: any[] = []; // 风险类型
    ThresholdTypeArr: any[] = []; // 阈值类型
    stockInfo: any = {};

    // 是否修改
    isUpdate: boolean = false;
    oldOuterOrderCode: string = '';
    serialNo: string = '';
    // 是否下单
    isPlaceOrder: boolean = false;
    transDialog: boolean = false;

    fundFilterList: any[] = [];
    stockCodeKey: string = '';
    stockNameKey: string = '';
    resultFilterList: any[] = [];

    calcPrice: number = 0;
    renderCountKey: number = 0;
    orderPrice: string = '';
    innerOrderDirectionData: any[] = [];
    orderDirectionData: any[] = [];
    pageResult: pages = {
        total: 0,
        currentPage: 1,
        pageSize: 10,
    };
    // 筛选后的试算结果
    filterRiskResultTable: any[] = [];
    positionTableKey: number = 0;
    resultSortList: any[] = [];

    riskOrderResultTable: any[] = [];
    orderCancelShow: boolean = false;
    riskOrderResultAfterKey: number = 0;

    instructionCache: any = {};
    stockInfoCache: any = {};

    selectEntryGroupCode = {
        calculateEntryGroup: [],
        excludeEntryGroup: [],
    };
    originOuterOrderCode: string = '';
    resourceCode: string = '';
    hasFutureRatio: boolean = true;

    // 监听产品代码变化，获取产品持仓
    @Watch('instructionCache.fundCode', { immediate: true, deep: true })
    onWatchFundCode(newValue, oldValue) {
        this.fundFilterList = [];
        this.positionTableKey++;
        if (JSON.stringify(newValue) != JSON.stringify(oldValue) && this.instructionCache.fundCode) {
            this.getFundPositionList(this.pages);
        }
        if (!this.instructionCache.fundCode) {
            this.fundPositionsListMsg.returnData.data = [];
            this.fundPositionsListMsg.returnData.total = 0;
        }
    }

    // 监听组合编码变化，获取产品持仓
    @Watch('instructionCache.fundAccountCode', { immediate: true, deep: true })
    onWatchFundAccountCode(newValue, oldValue) {
        this.fundFilterList = [];
        this.positionTableKey++;
        if (JSON.stringify(newValue) != JSON.stringify(oldValue)) {
            this.getFundPositionList(this.pages);
        }
    }

    // 获取要修改的指令信息
    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail?.instNo) {
            this.isUpdate = true;
            this.oldOuterOrderCode = this.detail.outerOrderCode;
            this.serialNo = this.detail.serialNo;
        }
    }

    async mounted() {
        this.resourceCode = getActiveMenuCode().defaultActive;

        this.getUserSelectEntryGroupList();
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取所有证券类别 (用于筛选订单方向)
        this.allStockType = await SGU_CACHE('StockType', '/dict/stockType/list', []);

        // 获取所有订单方向
        this.allOrderDirection = await SGU_CACHE('TradeDirection', '/dict/tradeDirections', []);
        // 获取风险类型字典
        this.entryType = this.Invest.entryType;
        // 获取比较方向字典
        this.compareDirection = this.Invest.CompareDirection;
        this.entryTypeArr = this.objToArr(this.Invest.entryType);

        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType);
        this.queryLayout();
    }

    // 所选产品是否含有期货保证金比例
    getFutureRatio(args: any) {
        this.hasFutureRatio = args;
    }

    /* ******************** 指令表单相关start ********************** */

    // 指令事件回调
    handleSettingValue(msg: any) {
        // let data = JSON.parse(JSON.stringify(msg[0]));

        this.instructionCache = JSON.parse(JSON.stringify(msg[0]));
    }

    getStockInfo(args: any) {
        this.stockInfo = args[0];
        this.stockInfoCache = this.stockInfo || {};
    }

    /* ******************** 指令表单相关end ********************** */

    /* *********************** 产品持仓start ********************** */

    // 产品持仓信息分页
    getFundPositionList(pages: any) {
        let form: any = {};
        // 判断是否带过滤条件
        if (!this.fundFilterList.length) {
            form = {
                businessType: '4',
                fundCode: [this.instructionCache.fundCode],
                fundAcCode: [this.instructionCache.fundAccountCode],
                paging: pages,
            };
        } else {
            form = {
                businessType: '4',
                stockCode: this.stockCodeKey,
                stockNameSt: this.stockNameKey,
                fundCode: [this.instructionCache.fundCode],
                fundAcCode: [this.instructionCache.fundAccountCode],
                paging: pages,
            };
        }

        // 获取产品持仓信息
        this.$axios.post('/position/stock', form).then((res: any) => {
            this.fundPositionsListMsg.returnData.data = res.list;
            this.fundPositionsListMsg.returnData.total = res.total;
            this.fundPositionsListMsg.returnData.data.forEach(ele => {
                for (let i = 0; i < this.allStockType.length; i++) {
                    const item = this.allStockType[i];
                    if (ele.stockType == item.dictKey) {
                        ele.stockType = item.dictKeyName;
                    }
                }
            });
        });
    }

    handleFilterFundPosition(filterList: any) {
        this.fundFilterList = filterList;
        this.stockCodeKey = '';
        this.stockNameKey = '';
        if (filterList.length) {
            let code = filterList.find(ele => ele.property === 'stockCode');
            let name = filterList.find(ele => ele.property === 'stockNameSt');
            this.stockCodeKey = code?.datas[0] || '';
            this.stockNameKey = name?.datas[0] || '';
        }
        this.getFundPositionList(this.pages);
    }

    /* *********************** 产品持仓end ********************** */

    /* ************************ 表格处理相关start *************************** */

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    // 获取可投余量、最大可交易量名称
    getShowName(name: string) {
        if (name == 'investableBalance') {
            return '可投余量';
        } else if (name == 'maxTradable') {
            return '最大可交易量';
        } else if (name == 'maxTradableMerge') {
            return '最大可交易量(汇总)';
        }
    }

    // 获取字段名
    getParamName(name: string) {
        return name == 'investableBalance' ? 'INVESTABLE_BALANCE_' : name == 'maxTradable' ? 'MAX_TRADABLE_' : 'MAX_TRADABLE_';
    }

    // 转表格筛选下拉框数据
    objToArr(param) {
        let list = [];
        for (let key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }

    customSortMethod({ data, sortList }) {
        const sortItem = sortList[0];
        // 取出第一个排序的列
        const { property, order } = sortItem;
        let YHList = [];
        let NoYHlist = [];
        let list = [];
        let key = /^[a-zA-Z]+$/;
        data.forEach(ele => {
            if (ele.entryCode.match('.*[A-Z]+.*') || ele.entryCode.match('.*[a-z]+.*')) {
                YHList.push(ele);
            } else {
                NoYHlist.push(ele);
            }
        });

        if (order === 'asc' || order === 'desc') {
            if (property === 'entryCode') {
                YHList.sort(this.compare('entryCode'));
                NoYHlist.sort(this.compare('entryCode'));
                list = NoYHlist.concat(YHList);
                if (order === 'desc') {
                    list.reverse();
                }
            } else {
                list = data.slice().sort(this.sortBy(property, order));
            }
        }
        return list;
    }

    compare(property) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if (value1.length < 10 && value2.length < 10) {
                var f = '0000000000'; // 10个0
                var aa = f.substring(0, 10 - ('' + value1).length) + value1;
                var bb = f.substring(0, 10 - ('' + value2).length) + value2;
                return aa > bb ? 1 : -1;
            } else {
                return value1 > value2 ? 1 : -1;
            }
        };
    }

    filterThresholdType({ value, row, column }) {
        return row.thresholdType == value;
    }

    filterEntryTypeMethod({ value, row, column }) {
        return row.entryType == value;
    }

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        const property = column['property'];
        return row[property].includes(option.data);
    }

    formatterCell({ cellValue }) {
        return cellValue || '--';
    }

    changeTable() {
        this.$nextTick(() => {
            let nodeName = [];
            let icon = [];
            if (!this.iconDom) {
                this.iconDom = document.querySelectorAll('.vxe-icon--funnel');
                this.iconDom.forEach((ele: any, index) => {
                    if (!['风险类型', '阈值类型'].includes(ele.parentNode.parentNode.children[0].innerHTML)) {
                        icon.push(index);
                    }
                });
                for (let i = 0; i < 8; i++) {
                    icon.forEach(ele => {
                        if (ele === i) {
                            this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
                        }
                    });
                }
            }
        });
    }

    /* ************************** 表格处理相关end ***************************** */

    /* **************************** 布局设置start ***************************** */
    // 获取页面布局信息
    async queryLayout() {
        this.calcLoading = true;
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/FUTURES_TRIAL')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);

            this.calcLoading = false;
        } else {
            this.selectedFieldList = this.tableColumns;
            this.showFieldList = this.tableColumns;
            this.calcLoading = false;
        }
        // 设置筛选、排序条件
        this.showFieldList.forEach((ele: any) => {
            if (['fundCode', 'assetCode', 'fundAccountCode', 'stockCode', 'entryCode'].includes(ele.id)) {
                this.$set(ele, 'sortable', true);
            }
            if (
                [
                    'fundCode',
                    'fundNameSt',
                    'assetCode',
                    'assetName',
                    'fundAccountCode',
                    'fundAccountName',
                    'stockCode',
                    'stockNameSt',
                    'entryCode',
                    'entryName',
                ].includes(ele.id)
            ) {
                this.$set(ele, 'filterMethod', this.filterHandler);
                this.$set(ele, 'filters', [{ data: '' }]);
                this.$set(ele, 'search', true);
            }
            if (ele.id == 'entryType') {
                // this.$set(ele, 'filterMethod', this.filterEntryTypeMethod);
                this.$set(ele, 'filters', this.entryTypeArr);
            }
            if (ele.id == 'thresholdType') {
                // this.$set(ele, 'filterMethod', this.filterThresholdType);
                this.$set(ele, 'filters', this.ThresholdTypeArr);
            }

            // 重新渲染表格
            this.changeTable();
            this.tableKey++;
        });
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
        this.iconDom = null;
        this.changeTable();
        this.tableKey++;
    }

    /* ************************** 布局设置end *******************************/

    /* ******************** 试算、下单处理start *********************** */
    // 校验提交参数
    verifyInstructionParam() {
        let param = this.instructionCache;

        if (!param.fundCode) {
            this.yh_message_warn('产品代码不可为空');
            return false;
        }
        if (!param.fundAccountCode) {
            this.yh_message_warn('组合编码不可为空');
            return false;
        }

        if (!param.reportCode) {
            this.yh_message_warn('合约代码不可为空');
            return false;
        }
        if (!param.orderDirection) {
            this.yh_message_warn('委托方向不可为空');
            return false;
        }
        if (!param.orderPrice) {
            this.yh_message_warn('指令价格不可为空');
            return false;
        }
        if (!param.orderAmount) {
            this.yh_message_warn('指令数量不可为空');
            return false;
        }
        if (!param.investType) {
            this.yh_message_warn('投资类型不可为空');
            return false;
        }

        if (!param.businessType) {
            this.yh_message_warn('业务类型不可为空');
            return false;
        }
        if (!this.hasFutureRatio) {
            this.yh_message_warn('所选产品和证券未查询到对应的期货保证金比例参数信息，请重新选择');
            return false;
        }

        return true;
    }

    // 补零
    fillZero(n) {
        let result = n.toString().length === 1 ? '0' + n : n;
        return result;
    }

    // 时间戳转换 yyyy-MM-dd
    formatTime(t = new Date()) {
        let d = new Date(t);
        let year = d.getFullYear();
        let month = d.getMonth() + 1;
        let date = d.getDate();
        let hours = d.getHours();
        let minutes = d.getMinutes();
        let seconds = d.getSeconds();
        let result = `${year}-${this.fillZero(month)}-${this.fillZero(date)} ${this.fillZero(hours)}:${this.fillZero(minutes)}:${this.fillZero(
            seconds
        )}`;
        return result;
    }

    // 重置按钮点击事件
    handleClickButtonReset() {
        this.renderCountKey++;
        this.$emit('reset', null);
        this.isUpdate = false;
        this.fundPositionsListMsg.returnData.data = [];
        this.fundPositionsListMsg.returnData.total = 0;
    }

    // 提交事件
    async handleSubmit(orderType: string) {
        const isUpdate = this.isUpdate;
        // 计算耗时
        let start = window.performance.now();

        // this.instructionCache.requestId = UUID() + '-' + new Date().getTime();
        this.instructionCache.orderType = orderType;
        this.instructionCache.instType = '7';
        this.instructionCache.outerOrderCode = this.instructionCache.requestId;
        this.instructionCache.orderUser = getUser().userCode;
        this.instructionCache.cancelType = '3';
        this.instructionCache.clearSpeed = '';
        this.instructionCache.marketCode = this.stockInfoCache.marketCode;
        this.instructionCache.operatorName = this.instructionCache.orderUser;
        this.instructionCache.orderLevel = '1';
        this.instructionCache.orderPriceType = '1';
        this.instructionCache.orderPurpose = '1';
        this.instructionCache.outerOrderCode = 'fg' + UUID() + '-' + new Date().getTime();
        this.instructionCache.requestId = 'rfg' + UUID() + '-' + new Date().getTime();
        this.instructionCache.businClass = this.instructionCache.businessType;
        // this.instructionCache.stockType = this.stockInfo.stockType;
        this.instructionCache.instructionCacheTypeName = this.instructionCache.businessType;
        this.instructionCache.instructionType = this.InstTypePojo[this.instructionCache.instType];

        // 试算表单
        let form: any = {
            orderType: orderType,
            multiType: '2',
            requestId: this.instructionCache.requestId,
            instructionType: this.InstTypePojo[this.instructionCache.instType],
            outOrderBatchCode: UUID() + new Date().getTime(),
            tradeUser: getUser().userCode,
            calculateEntryGroup: this.selectEntryGroupCode.calculateEntryGroup,
            excludeEntryGroup: this.selectEntryGroupCode.excludeEntryGroup,
            instList: [this.instructionCache],
        };
        if (orderType == '2') {
            this.instructionCache.cancelType = '1';
            form.cancelType = '1';
        }
        if (isUpdate) {
            form.excludeSerialNoSet = [this.serialNo];
        }

        this.originOuterOrderCode = this.instructionCache.outerOrderCode;

        // 校验参数规则
        if (!this.verifyInstructionParam()) {
            return;
        }
        // 获取当前提交时间 (试算/下单时间)
        this.calcTime = this.formatTime(new Date());
        const resList: any = await new Promise((resolve, reject) => {
            trialCalculate(form)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    this.calcLoading = false;
                    reject(err);
                });
        });

        if (resList) {
            // 风控结果
            this.riskResult = resList.thresholdType;
            this.result = resList.thresholdType;
            // 计算耗时
            let end = window.performance.now();
            this.takeTime = ((end - start) / 1000).toFixed(3) + '秒';

            let data = resList.resultList || [];
            // 根据产品代码 匹配产品名称
            data.forEach(ele => {
                ele.requestId = resList.requestId;

                for (let i = 0; i < this.fundCodeSelectData.length; i++) {
                    const item = this.fundCodeSelectData[i];
                    if (ele.fundCode == item.fundCode) {
                        ele.fundNameSt = item.fundNameSt;
                    }
                }
                ele.stockNameSt = this.stockInfo.stockNameSt;
            });

            this.riskOrderResultTable = JSON.parse(JSON.stringify(data));
            // data = data.filter((item) => item.thresholdType != '4');
            // data = data.sort(this.sortBy('thresholdType'));

            // this.riskResult = data[0]?.thresholdType || resList.thresholdType;
            // this.result = data[0]?.thresholdType || resList.thresholdType;
            // 如果结果是合规或者是试算就填充数据，否则等待用户选择完之后填充数据
            if (this.result == '0' || !this.isPlaceOrder) {
                this.resultFilterList = [];
                // this.pageChangeResult(1);
                this.riskResultTable = data;
                this.calcLoading = false;
            }
            if (!this.isPlaceOrder) {
                this.orderCancelShow = false;
                this.yh_message_success('提交试算信息成功');
            } else if (orderType == '2') {
                if (this.result == '0') {
                    this.orderCancelShow = false;
                    this.handleClickButtonReset();
                    this.handleResetResult();
                    const h = this.$createElement;
                    this.$message.success({
                        message: h('p', null, [
                            h('span', null, '本次风控下单结果为'),
                            h('span', { style: 'color: #70b603' }, '"合规"'),
                            h('span', null, '，已下单成功'),
                        ]),
                        showClose: true,
                        customClass: 'messageStyle',
                    });
                    if (isUpdate) {
                        this.handleUpdateCancel();
                    }
                    this.isUpdate = false;
                } else {
                    console.log('下单触发非合规');
                    this.riskOrderResultAfterKey++;
                    this.orderCancelShow = true;
                }
            }
        } else {
            this.handleResetResult();
        }
    }

    // 对象数组排序
    sortBy(props, sortType) {
        return function (a, b) {
            if (sortType == 'desc') {
                return b[props] - a[props];
            } else {
                return a[props] - b[props];
            }
        };
    }

    // 清空试算结果
    handleResetResult() {
        this.riskResultTable = [];
        this.riskResult = '';
        this.calcTime = '';
        this.takeTime = '';
    }

    // 试算按钮点击
    handleTestClick() {
        this.isPlaceOrder = false;
        this.orderCancelShow = false;
        this.handleSubmit('1');
    }

    // 下单按钮点击
    handlePlaceOrderClick() {
        this.result = '';
        this.isPlaceOrder = true;
        this.handleSubmit('2');
    }

    // 处理选择结果返回
    riskResultContinue() {
        console.log('继续下达');
        this.calcLoading = false;
        this.handleClickButtonReset();
        this.handleResetResult();
        // this.riskResultTable = this.riskOrderResultTable;
        if (this.isUpdate) {
            this.handleUpdateCancel();
        }
        this.yh_message_success('指令下达成功');
        this.isUpdate = false;
    }

    // 取消
    riskResultCancel() {
        this.calcLoading = false;
        // this.riskResultTable = [];
        console.log('终止下达');
        cancelCommonOrder({
            cancelOrderType: '2',
            tradeUser: getUser().userCode, // 当前用户
            tradeUserName: getUser().userName, // 当前用户
            orderType: '4',
            instructionType: '10',
            instNo: '',
            originOuterOrderCode: this.originOuterOrderCode,
            outerOrderCode: UUID() + '-' + new Date().getTime(),
            requestId: UUID() + '-' + new Date().getTime(),
            delOriginOuterOrderCodeList: [this.originOuterOrderCode],
        }).then(res => {
            this.yh_message_success('已终止指令下达');
        });
    }

    // 修改指令撤单
    handleUpdateCancel() {
        cancelCommonOrder({
            cancelOrderType: '2',
            tradeUser: getUser().userCode, // 当前用户
            tradeUserName: getUser().userName, // 当前用户
            orderType: '4',
            instructionType: '10',
            instNo: '',
            originOuterOrderCode: this.oldOuterOrderCode,
            outerOrderCode: UUID() + '-' + new Date().getTime(),
            requestId: UUID() + '-' + new Date().getTime(),
            delOriginOuterOrderCodeList: [this.oldOuterOrderCode],
        })
            .then(res => {})
            .catch(err => {
                this.yh_message_success(err);
            });
    }

    /* ******************************** 试算、下单处理end *************************** */

    /* ************************************ 条目组设置start ********************************** */
    openEntryGroup() {
        this.transDialog = true;
    }

    getEntryGroup(value: any) {
        this.selectEntryGroupCode.calculateEntryGroup = value.calculateEntryGroup;
        this.selectEntryGroupCode.excludeEntryGroup = value.excludeEntryGroup;
    }

    closeEntryDialog() {
        this.transDialog = false;
        this.getUserSelectEntryGroupList();
    }

    getUserSelectEntryGroupList() {
        this.$axios.get('/entry/group/user/select/list/' + this.resourceCode).then((res: any) => {
            res = res || [];
            let selectEntryGroupCode = {
                calculateEntryGroup: res.filter(item => item.instGroupType === '1' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
                excludeEntryGroup: res.filter(item => item.instGroupType === '2' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
            };
            this.selectEntryGroupCode.calculateEntryGroup = selectEntryGroupCode.calculateEntryGroup;
            this.selectEntryGroupCode.excludeEntryGroup = selectEntryGroupCode.excludeEntryGroup;
        });
    }

    /* ************************************ 条目组设置end ********************************** */
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';
@import '@/pages/risk-time/styles/risk-order';
</style>
<style lang="scss">
.messageStyle {
    background-color: #ecf9e3;
    border-color: #ecf9e3;
    font-size: 18px;
    .el-icon-success {
        color: #67c23a;
    }
}
</style>
